package com.bdqn.crm.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.crm.pojo.BasDict;
import com.bdqn.crm.pojo.CstService;
import com.bdqn.crm.pojo.SysUser;
import com.bdqn.crm.service.BasDictService;
import com.bdqn.crm.utils.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/dict")
public class DictController {

    @Resource
    private BasDictService basDictService;

    @RequestMapping("list")
    public String list(HttpServletRequest request, Model model, @RequestParam(value = "dictId",required = false) Integer dictId, @RequestParam(value = "dictItem",required = false) String dictItem, @RequestParam(required = false, defaultValue = "1") int pageIndex){
        Page<BasDict> page = new Page<>(pageIndex, 5);
        QueryWrapper<BasDict> queryWrapper = new QueryWrapper<>();
        //判断是否有查询条件
        queryWrapper.eq("dict_type","客户等级");
        if (dictId != null) {
            queryWrapper.eq("dict_id", dictId);      //模糊设置条件
        }
        if (dictItem != null && dictItem.trim() != "") {
            queryWrapper.like("dict_item", dictItem);
        }

        if (basDictService.count(queryWrapper) == 0) {     //此操作说明 数据库没有数据可展示，那么就全部清零
            page.setTotalElements(0);
            page.setContent(null);
        } else {
            page.setTotalElements(basDictService.count(queryWrapper));
            page.setContent(basDictService.selectPages(dictId, dictItem,(page.getNumber() - 1) * page.getPageSize(), page.getPageSize()));
        }

        model.addAttribute("dictId",dictId);
        model.addAttribute("dictItem",dictItem);
        model.addAttribute("dictPage", page);
        return "dict/list";
    }

    @RequestMapping("edit")
    public String edit(Model model,@RequestParam("dictId") Integer dictId){
        BasDict editDict = basDictService.getById(dictId);
        model.addAttribute("dict",editDict);
        return "dict/edit";
    }

    @RequestMapping("save")
    public String save(Model model,BasDict basDict){
        basDict.setDictType("客户等级");
        if(basDictService.saveOrUpdate(basDict)){
            return "redirect:/dict/list";
        }else{
            model.addAttribute("dict",basDict);
            return "dict/edit";
        }
    }

    @ResponseBody
    @RequestMapping("del/{dictId}")
    public String del(Map<String,String> map, @PathVariable("dictId") Integer dictId){
        if(basDictService.removeById(dictId)){
            map.put("delResult","true");
        }else{
            map.put("delResult","false");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("add")
    public String toAdd(){
        return "dict/add";
    }

}
